<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2016/12/22
 * Time: 16:40
 */
namespace AuctionBack\Logic;
use AuctionBack\Model\CarDealerModel;
use AuctionBack\Logic\CarReportLogic;
use AuctionCore\CarResource\CarModel;
use AuctionBack\Logic\CarOwnerLogic;
use AuctionBack\Model\RefundModel;
use AuctionBack\Logic\RecheckLogic;

class RefundLogic {

    protected $autoCheckFields = false;

    /**
     * 退车编号
     *
     * @var
     */
    protected $id;

    /**
     * 退车Model
     *
     * @var \Model|\Think\Model
     */
    protected $model;

    /**
     * RefundCar constructor.
     * @param $id
     */
    public function __construct($id)
    {
        $this->id = $id;
        $this->model = D('Refund','Model');
    }

    /**
     * 添加退车信息
     *
     * @param $data 退车数据
     * @return mixed
     */
    public static function add($data){
        $result = D('Refund','Model')->add($data);
        return $result;
    }

    /**
     * 修改退车信息
     *
     * @param $data 退车数据
     * @return bool
     */
    public function save($data){
        $id = $this->id;
        return D('Refund','Model')->where(['id'=>$id])->save($data);
    }

    /**
     * 根据来源获得退车信息
     *
     * @param $referId 来源id
     * @param $type 类型（自收/违约）
     * @return mixed
     */
    public static function getRefundCarByRefer($referId, $type){
        $map['refer_id'] = ['eq',$referId];
        $map['type'] = ['eq',$type];
        return D('Refund','Model')->where($map)->find();
    }

    /**
     * 得到退车列表
     *
     * @param int $page 当前第几页
     * @param int $size 每页显示条数
     * @param $params 参数
     * @return array
     */
    public static function getList($page = 1, $size = 10, $params){
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;
        $map = self::make_params($params);

        if($map === false ){
            return [
                'total' => 0,
                'list' => [],
            ];
        }
        if($params['status'] == 1){
            $order = 'create_time desc';
        }else if($params['status'] == 2){
            $order = 'next_trace_time desc';
        }else{
            $order = 'finish_time desc';
        }

        $total = D('Refund','Model')->relation(true)->where($map)->count();

        $list =  D('Refund','Model')->relation(true)->where($map)->limit($size)->page($page)->order($order)->select();
        $carModelObj = new CarModel();

        foreach ($list as $key => $value){
            $carInfo = $value['Cars'];

            $brand = $carModelObj->get_model_by_id($carInfo['brand_id'], 'brand');
            $series = $carModelObj->get_model_by_id($carInfo['series_id'], 'series');
            $model = $carModelObj->get_model_by_id($carInfo['model_id']);
            $list[$key]['car_model'] = $brand['name'] . $series['name'] . $model['name']; //车型

            //车牌号
            $list[$key]['plate_number'] = C("PLATE_PREFIX." . $carInfo['plate_prefix']) . $carInfo['plate_suffix'];
            //渠道来源
            $list[$key]['come_from'] = CarModel::getComeFromByCarId($carInfo['car_id']);
            //车辆类型
            $list[$key]['type_name'] = C('REFUND_CAR_TYPE')[$value['type']];
            //print_r($value['type']);die();
            $ownerId = $carInfo['owner_id'];
            $carOwner = CarOwnerLogic::getCarOwnerByMap(['owner_id' => $ownerId]);
            $list[$key]['car_owner_name'] = $carOwner['seller_name']; //车主名称
            $list[$key]['car_owner_phone'] = $carOwner['phone']; // 车主电话
            $list[$key]['car_sno'] = $carInfo['sno'];//车辆编号
        }

        return [
            'total' => $total,
            'list' => $list,
        ];
    }

    /**
     * 参数组装
     *
     * @param $params 参数数组
     * @return array
     */
    public static function make_params($params){
        $status = $params['status'];
        $map = [];
        $map['status'] = $status;
        $type = $params['type'];
        if(!empty($type)){
            $map['type'] = $type;
        }
        $carPlateNumber = $params['car_plate_number'];
        $sno = $params['sno'];

	    $carMap = [];
	    $mapSids = [];

	    if(!empty($params['location_area'])){
		    $carMap['location_area'] = ['in',$params['location_area']];
		    $CarsInfo = CarReportLogic::getCarInfos($carMap);
		    foreach ($CarsInfo as $key => $value){
			    $mapSids[] = $value['sid'];
		    }
		    if(empty($mapSids)){
			    return false;
		    }
	    }


        if(!empty($sno)){
	        $carMap['sno'] = $sno;
            $CarsInfo = CarReportLogic::getCarInfos($carMap);
	        $mapSidsTow = [];
            foreach ($CarsInfo as $key => $value){
	            $mapSidsTow[] = $value['sid'];
            }

	        if(empty($mapSids)){
		        $mapSids = $mapSidsTow;
	        }else{
		        $mapSids = array_intersect($mapSids,$mapSidsTow);
	        }

            if(empty($mapSids)){
                return false;
            }
        }

        if(!empty($carPlateNumber)){
            $where = [];
            $car_plate_number = trim($carPlateNumber);
            $car_plate_number_first = mb_substr($car_plate_number, 0, 1, 'UTF8');
            $car_plate_number_last = mb_substr($car_plate_number, 1, 7, 'UTF8');
            $plate_prefix = array_search($car_plate_number_first, C('PLATE_PREFIX'));
            $plate_suffix = substr($car_plate_number, 1);
            $where['plate_prefix'] = array('eq', $plate_prefix);
            if ($car_plate_number_last) {
                $where['plate_suffix'] = array('eq',$car_plate_number_last);
            }

            $CarsInfo = CarReportLogic::getCarInfos($where);

            $mapSidsNew = [];
            foreach ($CarsInfo as $key => $value){
                $mapSidsNew[] = $value['sid'];
            }
			if(empty($mapSids)){
				$mapSids = $mapSidsNew;
			}else{
				$mapSids = array_intersect($mapSids,$mapSidsNew);
			}
            if(empty($mapSids)){
                return false;
            }
        }

        if(!empty($mapSids)){
            $map['sid'] = ['in',$mapSids];
        }

        if($status == 3){
            $startTime = $params['start_time'];
            $endTime = $params['end_time'];
            if($startTime && !$endTime){
                $map['finish_time'] = ['egt',$startTime];
            }

            if(!$startTime && $endTime){
                $map['finish_time'] = ['elt',$endTime];
            }

            if($startTime && $endTime){
                $map['finish_time'] = [['egt', $startTime . " 00:00:00"], ['elt', $endTime . " 23:59:59"]];
            }

            if($params['finish_emp_id']){
                $map['finish_emp_id'] = ['eq',$params['finish_emp_id']];
            }
        }

        if($status == 2){
	        if($params['finish_emp_id']){
		        $map['finish_emp_id'] = ['eq',$params['finish_emp_id']];
	        }
        }
        return $map;
    }

    public function detail(){
        $map = [
            'id' => $this->id
        ];
        //$carModelObj = new ();

        $refundCarInfo = D('Refund','Model')->where($map)->find();
        $carId = $refundCarInfo['car_id'];

        $detail = D('Cars','Model')->where(['car_id'=>$carId])->find();
        //print_r($detail);die();
        //RefundModel::
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($detail['brand_id'], 'brand');
        $series = $cm->get_model_by_id($detail['series_id'], 'series');
        $model = $cm->get_model_by_id($detail['model_id']);
        $detail['refundInfo'] = $refundCarInfo;

		$detail['id'] = $refundCarInfo['id'];
		$detail['next_trace_time'] = $refundCarInfo['next_trace_time'];
		$detail['finish_emp_name'] = $refundCarInfo['finish_emp_name'];
		$detail['finish_time'] = $refundCarInfo['finish_time'];
		$detail['order_id'] = $refundCarInfo['order_id'];
		$detail['selected_procedures'] = explode('、',$refundCarInfo['procedures']);
		//print_r($detail['selected_procedures']);
		$detail['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
		$detail['car_color'] = C('CAR_COLOR.' . $detail['car_color']);
		$detail['emission'] = C('INT_EMISSION_STD.' . $detail['emission']);
		$detail['plate_prefix'] = C('PLATE_PREFIX.' . $detail['plate_prefix']);
		$detail['pointer_mileage'] = formatMileage($detail['pointer_mileage']);
		$detail['transfer_limit'] = C('TRANSFER_LIMIT.' . $detail['transfer_limit']);
		$detail['comefrom'] = CarModel::getComeFromByCarId($carId);


        $ownerId = $detail['owner_id'];
        $ownerInfo = D('CarOwner','Model')->where(['owner_id',$ownerId])->find();
        $detail['seller_name'] = $ownerInfo['seller_name'];
        $detail['phone'] = $ownerInfo['phone'];
        $addr = new \AuctionCore\Other\Address();
        //echo $ownerInfo['location_area'];die();
        $detail['first_reg_city'] = $addr->get_name_by_code($ownerInfo['first_reg_city']);
        $detail['location_area'] = $addr->get_name_by_code($ownerInfo['location_area']);

        $type = $refundCarInfo['type'];
        $referId = $refundCarInfo['refer_id'];
        $detail['create_time'] = $refundCarInfo['create_time'];
        if($type == 1){ //违约车辆
            $carInfo = M('breach_car')->where(['bc_id'=>$referId])->find();
        }else{ //自收车辆
            $carInfo = M('self_receive_car')->where(['src_id'=>$referId])->find();
        }
        $detail['type'] = $refundCarInfo['type'] == 1 ? '违约车辆':'自收车辆';
        $detail['emp_name'] = $carInfo['emp_name'];
        $detail['remark'] = $carInfo['remark'];
        $detail['back_reason'] = C('BACK_RESON')[$refundCarInfo['back_reason']];

		$recheckInfo = RecheckLogic::getDataBySid($refundCarInfo['sid']);
		$detail['procedures'] = explode('、',$recheckInfo['procedures']);
		return $detail;
	}

}